﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net;
using System.Xml.Serialization;

namespace _1041326_1041339_1041433
{
    public partial class MasterPage : System.Web.UI.MasterPage
    {
        String url = "http://localhost:1871/Service.svc";
        string email = "";
        private string checkUser(string email)
        {
            var requestURL = url + "/user/getAll";
            WebRequest wr = WebRequest.Create(requestURL);
            WebResponse wp = wr.GetResponse();
            XmlSerializer serial = new XmlSerializer(typeof(ArrayOfNguoiDungDTO));
            ArrayOfNguoiDungDTO ds = (ArrayOfNguoiDungDTO)serial.Deserialize(wp.GetResponseStream());
            for (int i = 0; i < ds.Items.Length; i++)
            {
                if (ds.Items[i].Email == email)
                    return ds.Items[i].MaNguoiDung;
            }
            return null;
        }

        private void ShowAuthenticateMessage()
        {
            if (Session["Email"] != null)
            {
                
                email = Session["Email"].ToString();
                Session["Username"] = checkUser(email);
                lbUsername.Text = checkUser(email);
                lbEmail.Text = email;
                if (Session["Username"] == null)
                {
                    // them
                }
                if (Session["role"]!=null)
                    pnLinkAdmin.Visible = true;
                LoginPanel.Visible = false;
                AuthenticatedPanel.Visible = true;
            }
        }

        private void ShowLogin()
        {
            if (Session["Email"] == null)
            {

                LoginPanel.Visible = true;
                AuthenticatedPanel.Visible = false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ShowAuthenticateMessage();
                ShowLogin();
                //DataBind();
            }
        }
        protected void lbkLogout_Click(object sender, EventArgs e)
        {
            //hủy session
            Session["Email"] = null;
            Session["Username"] = null;
            Session["role"] = null;
            Response.Redirect("~/UserPages/HomePage.aspx");
        }
    }
}